package avicit.bdp.dms.oauth2.validator;

import avicit.bdp.dms.tdm.dto.AppClientDTO;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * TODO
 *
 * @author xugb
 * @date 2024/4/12 15:16
 */

public class ClientCredentialsClientDetailsValidator extends AbstractOauthTokenValidator {
    private static final Logger LOG = LoggerFactory.getLogger(ClientCredentialsClientDetailsValidator.class);

    public ClientCredentialsClientDetailsValidator(OAuthTokenRequest oauthRequest) {
        super(oauthRequest);
    }

    @Override
    protected OAuthResponse validateSelf(AppClientDTO appClientDTO) throws OAuthSystemException {
        String grantType = this.grantType();
        if (!appClientDTO.getGrantTypes().contains(grantType)) {
            LOG.debug("Invalid grant_type '{}', client_id = '{}'", grantType, appClientDTO.getClientId());
            return this.invalidGrantTypeResponse(grantType);
        } else {
            String clientSecret = this.oauthRequest.getClientSecret();
            if (clientSecret != null && clientSecret.equals(appClientDTO.getClientSecret())) {
                Set<String> scopes = this.oauthRequest.getScopes();
                return !this.excludeScopes(scopes, appClientDTO) ? null : this.invalidScopeResponse();
            } else {
                LOG.debug("Invalid client_secret '{}', client_id = '{}'", clientSecret, appClientDTO.getClientId());
                return this.invalidClientSecretResponse();
            }
        }
    }
}
